package com.project.aspect;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

@Component
@Aspect
public class ServiceAspect {
    private static SqlSessionFactory factory;
    static {
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint){

        //方法执行前加开启session连接
        SqlSession session = factory.openSession();

        try {
            //得到目标对象
            Object targetObj = joinPoint.getTarget();
            //得到该对象中的所有属性集合
            Field[] fieldArray = targetObj.getClass().getDeclaredFields();
            //遍历属性获取接口属性
            for (Field f : fieldArray){
                //是接口就初始化mapper属性
                if (f.getType().isInterface()){
                    f.setAccessible(true);
                    //获得mapper属性对象  f.getType()传入该属性的类型---mapper接口
                    Object mapperObj = session.getMapper(f.getType());
                    //初始化，将赋值之后的mapper对象替换目标属性对象
                    f.set(targetObj,mapperObj);
                }
            }
            //执行目标方法后，得到目标方法的返回值
            Object returnObj = joinPoint.proceed();

            //提交
            session.commit();
            return returnObj;
        } catch (Throwable throwable) {
            //产生异常就回滚
            session.rollback();
            throwable.printStackTrace();

        }
        finally {
            //关闭session连接
            session.close();
        }

        return null;
    }
}
